package com.yixun.service.impl;

import com.alibaba.fastjson.JSON;
import com.yixun.entity.LoginLogs;
//import com.yixun.entity.YxMenu;
import com.yixun.entity.YxMenu;
import com.yixun.entity.YxUser;
import com.yixun.mapper.LoginLogsMapper;
import com.yixun.mapper.UserMapper;
import com.yixun.service.*;
import com.yixun.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    private final UserMapper userMapper;

    private final LoginLogsMapper loginLogsMapper;

    @Autowired
    private MenuService menuService;

    private final RedisService redisService;

    private final LogSetService logSetService;

    private final RoleService roleService;

    public UserServiceImpl(UserMapper userMapper, LoginLogsMapper loginLogsMapper, RedisService redisService, LogSetService logSetService, RoleService roleService) {
        this.userMapper = userMapper;
        this.loginLogsMapper = loginLogsMapper;
        this.redisService = redisService;
        this.logSetService = logSetService;
        this.roleService = roleService;
    }


    @Override
    public Map<String, Object> login(ParameterMap pm, HttpSession session, String rip) {
        YxUser user = userMapper.getUserInfo(pm);
        if (null == user || null == user.getUser_id()) {
            return ResponseModel.getModel("账号或密码错误！","FAIL",null);
        }
        if (user.getUser_status() != 0) {
            return ResponseModel.getModel("账号异常！","FAIL",null);
        }
        ServletContext servletContext = session.getServletContext();
        Map<String,YxUser> globalUser = (Map<String, YxUser>) servletContext.getAttribute(Const.GLOBAL_SESSION);
        String user_name = pm.getString("user_name");
        if (null == globalUser) {
            globalUser = new HashMap<>();
        } else {
            globalUser.remove(user_name);
        }
        user.setPassword("******");
        user.setIp(rip);
        globalUser.put(user_name, user);
        session.setMaxInactiveInterval(3600);
        session.setAttribute(Const.SESSION_USER, user);
        servletContext.setAttribute(Const.GLOBAL_SESSION, globalUser);
        LoginLogs loginLogs = new LoginLogs();
        loginLogs.setAudit_id(new FormatUtil().getUUID());
        loginLogs.setUser_id(user.getUser_id());
        loginLogs.setUser_name(user.getUser_name());
        loginLogs.setAudit_des(LogUtil.LOGIN);
        loginLogs.setAudit_time(DateUtil.getDateTimeString(new Date()));
        loginLogs.setIp(rip);
        loginLogsMapper.insertLoginLog(loginLogs);
            return ResponseModel.getModel("OK","SUCCESS",null);
    }

    @Override
    public Map<String, Object> getUserBySession(HttpSession session) {
        YxUser sessionUser = (YxUser) session.getAttribute(Const.SESSION_USER);
        return ResponseModel.getModel("OK","SUCCESS",sessionUser);

    }

    @Override
    public String menuListToJsonStrByUserID(String user_id) {
        List<YxMenu> menuList = menuService.getMenuListByUserId(user_id);
        return "[{\"children\":["+menuListToStrHandl(menuList,menuService.getChildMenuListByID(menuList,"1"))+"]}]";
    }

    @Override
    public List<YxUser> getUserList(Map<String, String> map) {
        List<YxUser> userList = userMapper.getUserList(map);
        for (YxUser user: userList) {
            user.setRole_name(roleService.getRoleNameByUserId(user.getUser_id()));
        }
        return userList;
    }

    @Override
    public String getUserCount(Map<String, String> map) {
        return userMapper.getUserCount(map);
    }

    @Override
    @Transactional
    public int insertUser(YxUser sessionUser, YxUser user) {
        int row;
        YxUser paramUser = createUserNameAndPwd(user);
        paramUser.setUser_id(new FormatUtil().getUUID());
        paramUser.setAdd_user(sessionUser.getUser_id());
        paramUser.setAdd_time(DateUtil.getDateTimeString(new Date()));
        row = userMapper.insertUser(paramUser);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.ADD, "用户", JSON.toJSONString(paramUser), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    public YxUser getUserBean(String user_id) {
        return userMapper.getUserBean(user_id);
    }

    @Override
    @Transactional
    public int updateUser(YxUser sessionUser, YxUser user) {
        int row;
        user.setUpdate_user(sessionUser.getUser_id());
        user.setUpdate_time(DateUtil.getDateTimeString(new Date()));
        row = userMapper.updateUser(user);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.UPDATE, "用户", JSON.toJSONString(user), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int delUser(YxUser sessionUser, Map map) {
        int row;
        row = userMapper.delUser(map);
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.DELETE, "用户", JSON.toJSONString(map), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int moveUser(YxUser sessionUser, Map map) {
        int row;
        row = userMapper.moveUser(map);
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.MOVE, "用户", JSON.toJSONString(map), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    public int setUserStatus(Map map) {
        return userMapper.setUserStatus(map);
    }

    @Override
    @Transactional
    public int resetPassword(YxUser sessionUser, Map map) {
        int row;
        map.put("new_pw",new MD5Util().MD5((String) map.get("new_pw")));
        row = userMapper.resetPassword(map);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.UPDATE, "用户密码", JSON.toJSONString(map), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    public List<YxUser> getAllUserList() {
        return userMapper.getAllUserList();
    }

    @Override
    @Transactional
    public int updateSimple(YxUser sessionUser, YxUser user) {
        int row;
        row = userMapper.updateSimple(user);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.UPDATE, "个人信息", JSON.toJSONString(user), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    public YxUser checkOldPw(String user_name, Map<String, String> map) {
        String password = new MD5Util().MD5(map.get("pass_word"));
        map.put("password", password);
        map.put("user_name", user_name);
        return userMapper.checkOldPw(map);
    }

    /**
     * 生成后台用户的账号和密码
     * ADM+3位流水  密码Adm@+3位流水
     */
    public YxUser createUserNameAndPwd(YxUser user){
        Long adm_code = redisService.incr("adm_code", 1L);
        String s = new FormatUtil().numberComplement(4, adm_code);
        user.setUser_name("ADM" + s);
        user.setPassword(new MD5Util().MD5("Adm@" + s));
        return user;
    }

    /**
     * 递归处理list转json字符串
     * @param menuList
     * @param childList
     * @return
     */
    public String menuListToStrHandl(List<YxMenu> menuList, List<YxMenu> childList){
        String json_str = "";
        if (null != childList && childList.size() > 0) {
            for (YxMenu menu: childList) {
                json_str += ",{";
                json_str += "\"id\":"+menu.getMenu_id()+",\"text\":\""+menu.getMenu_name()+"\",\"attributes\":{\"thumb\":\""+menu.getCss_name()+"\",\"url\":\""+menu.getMenu_url()+"\",\"handls\":\""+menu.getHandls()+"\"}";
                List<YxMenu> child_m_list = menuService.getChildMenuListByID(menuList, menu.getMenu_id()+"");
                if (null != child_m_list && child_m_list.size() > 0) {
                    json_str += ",\"children\":["+menuListToStrHandl(menuList,child_m_list)+"]";
                }
                json_str += "}";
            }
        }
        if (!"".equals(json_str)) {
            json_str = json_str.substring(1);
        }
        return json_str;
    }
}
